import { defineStore } from 'pinia'
import { ref } from 'vue'

interface Product {
  id: string
  name: string
  image_url: string
  click_url?: string
}

interface PurchasedProduct {
  order_id: string
  product: Product
  expire_time: string
  status: string
}

export const useHomeStore = defineStore('home', () => {
  const hasCompanyCard = ref(false)
  const purchasedProducts = ref<PurchasedProduct[]>([])
  const loading = ref(false)

  // 获取已购买的商品列表
  async function fetchPurchasedProducts() {
    loading.value = true
    try {
      const res = await uni.request({
        url: `https://52d47b77.r34.cpolar.top/api/user-products/`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${uni.getStorageSync('userInfo')?.access_token}`,
          'Content-Type': 'application/json'
        },
        data: {
          phone: uni.getStorageSync('userInfo')?.phone,
          timestamp: Date.now(),
          debug: true
        }
      })
      console.log(res,'res78897944')

      const data = res.data as any
      if (Array.isArray(data)) {
        purchasedProducts.value = data
      }
    } catch (error) {
      console.error('获取已购买商品失败:', error)
      uni.showToast({
        title: '获取商品列表失败',
        icon: 'none'
      })
    } finally {
      loading.value = false
    }
  }

  return {
    hasCompanyCard,
    purchasedProducts,
    loading,
  }
})